package com.chenhb.watermarkutils;


import com.chenhb.watermarkutils.bo.WatermarkBo;
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextWrappingStyle;
import com.spire.doc.fields.DocPicture;

import java.io.*;

/**
 * word添加图片水印工具
 *
 * @author 陈海波
 * @date 2021-04-21
 */
public class WordImageWatermark extends AbstractWatermark {
    /**
     * word添加图片水印
     *
     * @param watermarkBo
     * @return
     * @throws IOException
     */
    public static ByteArrayOutputStream mark(WatermarkBo watermarkBo) throws IOException {
        //加载Word文档
        Document doc = new Document();

        doc.loadFromStream(new FileInputStream(watermarkBo.getResourceFile()), FileFormat.Docx);

        //加载图片
        DocPicture picture = new DocPicture(doc);
        picture.loadImage(new FileInputStream(watermarkBo.getWatermarkImageFile()));
        picture.setHeight(watermarkBo.getHeight());
        picture.setWidth(watermarkBo.getWidth());
        //设置图片环绕方式
        picture.setTextWrappingStyle(TextWrappingStyle.Behind);

        //遍历所有section
        for (int n = 0; n < doc.getSections().getCount(); n++) {
            Section section = doc.getSections().get(n);

            //获取section的页眉
            HeaderFooter header = section.getHeadersFooters().getHeader();

            Paragraph paragrapg1;
            //获取或添加段落
            if (header.getParagraphs().getCount() > 0) {
                paragrapg1 = header.getParagraphs().get(0);
            } else {
                paragrapg1 = header.addParagraph();
            }

            //复制图片，并添加图片到段落
            picture = (DocPicture) picture.deepClone();
            picture.setVerticalPosition(watermarkBo.getOffsetY());
            picture.setHorizontalPosition(watermarkBo.getOffsetX());
            picture.setRotationEx(watermarkBo.getDegree());
            paragrapg1.getChildObjects().add(picture);
        }

        //保存文档
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        doc.saveToStream(output, FileFormat.Docx);
        doc.dispose();
        return output;
    }
}
